import { createRouter, createWebHistory } from 'vue-router'
// 1. 重新引入 defineAsyncComponent（之前去掉是错误的）
import { defineAsyncComponent } from 'vue'
import { useUserStore } from '@/store/modules/user/user.js'
import BaseLoading from '../components/loading/BaseLoading.vue'
import ErrorComponent from '../components/loading/ErrorComponent.vue'

// 1. 用 import.meta.glob 批量导入 views 下所有 .vue 组件（支持多级目录）
// 说明：
// - ../views/**/*.vue：匹配 views 下所有子目录的 .vue 文件
// - { eager: false }：保持懒加载（默认就是 false，可省略）
const asyncComponents = import.meta.glob('../views/**/*.vue')

// 2. 重写异步组件加载函数（兼容 Vite 动态导入规则）
const loadAsyncComponent = (componentPath) => {
  // 拼接组件路径（与 import.meta.glob 的匹配规则一致）
  const componentKey = `../views/${componentPath}.vue`
  // 从批量导入的组件中获取目标组件（必须用 componentKey 精确匹配）
  const componentLoader = asyncComponents[componentKey]

  if (!componentLoader) {
    console.error(`未找到组件：${componentKey}`)
    return ErrorComponent // 组件不存在时显示错误组件
  }

  // 直接返回加载函数（无需 defineAsyncComponent，Vue Router 原生支持）
  return {
    loader: componentLoader, // 从 glob 中获取的懒加载函数
    loadingComponent: BaseLoading,
    delay: 200,
    timeout: 5000,
    errorComponent: ErrorComponent,
  }
}

const routes = [
  // 注意：componentPath 格式不变（仍为 "home/Home" 这种多级路径），内部会通过 glob 匹配
  { path: '/home', component: loadAsyncComponent('home/Home'), alias: '/' },
  {
    path: '/message', component: loadAsyncComponent('message/Message'),
    children: [
      { path: 'followers', component: loadAsyncComponent('message/FollowersPage') },
      { path: 'likes', component: loadAsyncComponent('message/LikesPage') },
      { path: 'mentions', component: loadAsyncComponent('message/MentionsPage') },
      { path: 'comments', component: loadAsyncComponent('message/CommentsPage') },
    ]
  },
  { path: '/video', component: loadAsyncComponent('video/Video') },
  {
    path: '/user', component: loadAsyncComponent('user/User'),
    children: [
      { path: 'follows', component: loadAsyncComponent('user/MyFollowsPage') },
      { path: 'fans', component: loadAsyncComponent('user/MyFansPage') },
    ]
  },
  { path: '/follow', component: loadAsyncComponent('follow/Follow') },
  {
    path: '/search', component: loadAsyncComponent('search/search'),
    children: [
      { path: 'video', alias: '', component: loadAsyncComponent('search/VideoSearch') },
      { path: 'user', component: loadAsyncComponent('search/UserSearch') },
    ]
  },
  { path: '/profile/:userId', component: loadAsyncComponent('home/profile') },
  { path: '/contact-picker', component: loadAsyncComponent('ContactPicker/ContactPicker') },
  { path: '/ChatWith', component: loadAsyncComponent('ChatWith/ChatWith') },
]

const router = createRouter({
  history: createWebHistory(),
  routes
})

const whiteList = ['/home', '/']

router.beforeEach(async (to, from, next) => {
  if (whiteList.includes(to.path)) {
    next()
    return
  }
  const userStore = useUserStore()
  const isLogin = await userStore.checkLogin()
  if (isLogin) {
    next()
  } else {
    userStore.showLogin()
    next(false)
  }
})

export default router